package com.yc.fav.demo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class D1111 {

    private static int a;
    String b;
    public char c;

    public static void main(String[] args)
            throws InstantiationException, IllegalAccessException,
            NoSuchMethodException, InvocationTargetException,
            NoSuchFieldException {
        A a = A.class.newInstance();
        try{
            B b = B.class.newInstance(); // new B(); 无参构造函数失效
        } catch(InstantiationException e){
            System.out.println(e.getMessage());
        }
        // 获取一个构造函数
        Constructor<B> bc = B.class.getDeclaredConstructor(String.class);
        // 调用由参数构造函数
        Object b = bc.newInstance("张三");

       // b.b = "admin"; b.b 是私有属性
        Field b1 = b.getClass().getDeclaredField("b");
        b1.setAccessible(true); // 设置强制访问
        b1.set(b, "李四");
        System.out.println(b1.get(b));  // 获取 b.b 的值

        // 获取父类类对象  aClass ==> A.class
        Class<?> aClass = b.getClass().getSuperclass();
        // 获取 A 的 Hello 方法
        Method hello = aClass.getDeclaredMethod("hello", String.class);
        hello.setAccessible(true);
        // 调用 方法
        hello.invoke(b, "王五");

    }

    protected void test() throws ClassNotFoundException {
        Class<D1111> cls = D1111.class;

        Object o = new D1111();
        Class<?> cls1 = o.getClass();

        Class<?> cls2 = Class.forName("com.yc.fav.demo.D1111");

        System.out.println(cls == cls1);
        System.out.println(cls == cls2);

        System.out.println("========= 共有方法 ===========");
        for (Method method : cls.getMethods()) {
            System.out.println(method.getName());
        }
        System.out.println("========== 该类定义的方法 ==========");
        for (Method method : cls.getDeclaredMethods()) {
            System.out.println(method.getName());
        }

        System.out.println("========= 共有属性 ===========");
        for (Field field : cls.getFields()) {
            System.out.println(field.getName());
        }

        System.out.println("========= 该类定义的属性 ===========");
        for (Field field : cls.getDeclaredFields()) {
            System.out.println(field.getName());
        }
    }

}

class A {
    int a;

    // private A(){}

    private void hello(String name) {
        System.out.println("hello " + name);
    }
}

class B extends A {
    private String b;

    public B(String b){
        this.b = b;
    }
    public B(String b, int a){
        this.b = b;
    }

    public void play() {
        System.out.println("play game");
    }
}
